<?php


namespace PKFrame\Lib;
defined('PATH_PK') or die();


class Redirect extends Response
{

    protected $options = [];

    // URL参数
    protected $params = [];

    public function __construct($data = '', $code = 302, array $header = [], array $options = [])
    {
        parent::__construct($data, $code, $header, $options);

        $this->cacheControl('no-cache,must-revalidate');
    }

    /**
     * 处理数据
     * @access protected
     * @param  mixed $data 要处理的数据
     */
    protected function output($data)
    {
        $this->header['Location'] = $this->getTargetUrl();
    }

    /**
     * 获取跳转地址
     * @access public
     * @return string
     */
    public function getTargetUrl(): ?string
    {
        if (strpos($this->data, '://') || (0 === strpos($this->data, '/') && empty($this->params))) {
            return $this->data;
        }
        return null;
    }

    public function params($params = []): Redirect
    {
        $this->params = $params;

        return $this;
    }

    /**
     * 跳转到上次记住的url
     * @param string|null $url 闪存数据不存在时的跳转地址
     * @return $this
     */
    public function restore(string $url = null): Redirect
    {
        $this->data = $url;

        return $this;
    }
}
